package org.collector.process;

import java.util.HashMap;
import java.util.Vector;

import org.collector.baseoper.ClientsWithStatu;
import org.collector.data.iodata.IUrl;

public class CoreThreadsManage {
	private ClientsWithStatu clientsWithStatu;
	private final static int TASKPROC_COUNT = 50;
	private final static int TASKALLOC_COUNT = 1;
	private Vector<TaskAllocRunable> vct_taskAllocs;
	private HashMap<TaskAllocRunable,Thread> vct_taskAllocsMap;
	private Vector<TaskProcessRunnable> vct_taskProcs;
	private HashMap<TaskProcessRunnable,Thread> vct_taskProcsMap;
	public CoreThreadsManage(final String proxyPath,final int taskproc_count,final int taskalloc_count){
		clientsWithStatu = new ClientsWithStatu();
		clientsWithStatu.loadProxies(proxyPath);
		vct_taskAllocs = new Vector<TaskAllocRunable>();
		vct_taskProcs = new Vector<TaskProcessRunnable>();
		vct_taskAllocsMap = new HashMap<TaskAllocRunable,Thread>();
		vct_taskProcsMap = new HashMap<TaskProcessRunnable,Thread>();
		for(int i = 0; i < taskproc_count; ++i)
			vct_taskProcs.add(new TaskProcessRunnable(clientsWithStatu));
		for(int i = 0; i < taskalloc_count; ++i)
			vct_taskAllocs.add(new TaskAllocRunable(clientsWithStatu));
	}
	public CoreThreadsManage(final String proxyPath){
		this(proxyPath,TASKPROC_COUNT,TASKALLOC_COUNT);
	}
	public void start(){
		for(TaskAllocRunable r: vct_taskAllocs){
			Thread t = new Thread(r);
			vct_taskAllocsMap.put(r, t);
			t.start();
		}
		for(TaskProcessRunnable p: vct_taskProcs){
			Thread t = new Thread(p);
			vct_taskProcsMap.put(p, t);
			t.start();
		}
	}
	public void close(){
		for(TaskAllocRunable r: vct_taskAllocsMap.keySet()){
			r.close();
			try {
				vct_taskAllocsMap.get(r).join();
			} catch (InterruptedException e) {
			}
		}
		for(TaskProcessRunnable r: vct_taskProcsMap.keySet()){
			r.close();
			try {
				vct_taskProcsMap.get(r).join();
			} catch (InterruptedException e) {
			}
		}
		clientsWithStatu.close();
	}
	public boolean addTask(IUrl url){
		return clientsWithStatu.addTask(url);
	}
	public Vector<TaskAllocRunable> getVct_taskAllocs() {
		return vct_taskAllocs;
	}
	public ClientsWithStatu getClientsWithStatu() {
		return clientsWithStatu;
	}
}
